package com.goldcn.order.controller;

import com.goldcn.common.CommonTools;
import com.goldcn.common.CusAccessObjectUtil;
import com.goldcn.common.HttpUtil;
import com.goldcn.common.model.DataResult;
import com.goldcn.common.util.IdGen;
import com.goldcn.config.ErpInterfaceCfg;
import com.goldcn.config.ProConstants;
import com.goldcn.enumeration.ErpInterfaceCfgEnum;
import com.goldcn.interceptor.SystemContext;
import com.goldcn.order.dao.CountOrderMapper;
import com.goldcn.order.dao.ErrorEsMapper;
import com.goldcn.order.dao.OrderInfoMapper;
import com.goldcn.order.dao.OrderItemMapper;
import com.goldcn.order.dto.*;
import com.goldcn.order.erpVo.ResultData;
import com.goldcn.order.model.CountOrder;
import com.goldcn.order.model.ErrorEs;
import com.goldcn.order.model.OrderInfo;
import com.goldcn.order.model.OrderLogistics;
import com.goldcn.order.service.CommissionUserService;
import com.goldcn.order.service.OrderIndexService;
import com.goldcn.order.service.OrderService;
import com.goldcn.order.vo.OrderCountVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * Created by 1111 on 2016/11/17.
 */
@Api(value = "订单管理")
@RestController
@RequestMapping(value = "/order")
public class OrderController {
    @Autowired
    OrderService orderService;

    @Autowired
    OrderInfoMapper orderInfoMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    ErrorEsMapper errorEsMapper;

    @Autowired
    ErpInterfaceCfg erpInterfaceCfg;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    CountOrderMapper countOrderMapper;

    @Autowired
    OrderIndexService orderIndexService;

    @Autowired
    CommissionUserService commissionUserService;

    private Logger logger = Logger.getLogger(OrderController.class);


    @ApiOperation(value = "新增订单,购物车购买")
    @RequestMapping(method = RequestMethod.POST)
    public Object addOrder(@RequestBody List<AddOrderDto> addOrderDtoList) throws Exception {
        return orderService.addOrder(addOrderDtoList, false);
    }

    @ApiOperation(value = "新增订单,购物车购买")
    @RequestMapping(value = "/b2b", method = RequestMethod.POST)
    public Object addOrderForB2b(@RequestBody List<AddOrderDto> addOrderDtoList) throws Exception {
        return orderService.addOrder(addOrderDtoList, true);
    }

    @ApiOperation(value = "按userID查询上一次填写的发票抬头")
    @RequestMapping(value = "/invoices/{userID}", method = RequestMethod.GET)
    public Object getLatestInvoicesByUserID(@PathVariable Long userID) {
        return orderService.getLatestInvoicesByUserID(userID);
    }

    @ApiOperation(value = "按userID查询上一次填写的发票抬头")
    @RequestMapping(value = "/invoicesV2/{userID}", method = RequestMethod.GET)
    public Object getLatestInvoicesByUserIDV2(@PathVariable Long userID) {
        return orderService.getLatestInvoicesByUserIDV2(userID);
    }

    @ApiOperation(value = "根据userID查询未付款及其未收货数量[unpaidQty待付款，unReceiptQty待收货]")
    @RequestMapping(value = "/tips/{userID}", method = RequestMethod.GET)
    public Object selectTipsByUserID(@PathVariable Long userID) {
        return orderService.selectTipsByUserID(userID);
    }

    @ApiOperation(value = "复制下单/立即购买")
    @RequestMapping(value = "/copyOrDirectBuy", method = RequestMethod.POST)
    public Object copyOrder(@RequestBody CopyOrDirectBuyDto buyDto) {
        return orderService.copyOrDirectBuyOrder(buyDto, false);
    }

    @ApiOperation(value = "复制下单/立即购买")
    @RequestMapping(value = "/b2b/copyOrDirectBuy", method = RequestMethod.POST)
    public Object copyOrderForB2b(@RequestBody CopyOrDirectBuyDto buyDto) {
        return orderService.copyOrDirectBuyOrder(buyDto, true);
    }

    @ApiOperation(value = "复制下单获取商品最新信息快照")
    @RequestMapping(value = "/goodsForCopy/{orderID}", method = RequestMethod.GET)
    public Object copyOrderGoodsInfo(@PathVariable Long orderID) throws Exception {
        return orderService.copyOrderGoodsInfo(orderID);
    }

    @ApiOperation(value = "按id查询订单详情[1查询订单详细信息，2只查询订单信息]")
    @RequestMapping(value = "/{orderID}/{type}", method = RequestMethod.GET)
    public Object selectByOrderID(@PathVariable Long orderID, @PathVariable int type) throws Exception {
        return orderService.selectByOrderID(orderID, 1l, type);
    }

    @ApiOperation(value = "按ids查询订单详情[1查询订单详细信息，2只查询订单信息]")
    @RequestMapping(value = "/orderInfos", method = RequestMethod.POST)
    public Object selectByOrderIDList(@RequestBody OrderIDDto orderIDDto) throws Exception {
        return orderService.selectByOrderIDS(orderIDDto);
    }


    @ApiOperation(value = "按payno查询订单详情[外部系统查询用]")
    @RequestMapping(value = "/payno/{payNO}", method = RequestMethod.GET)
    public Object selectByOrderPayNO(@PathVariable String payNO) throws Exception {
        return orderService.selectOrderByPayNO(payNO);
    }

    @ApiOperation(value = "按pointPayno查询订单详情[外部系统查询用]")
    @RequestMapping(value = "/pointPayno/{payNO}", method = RequestMethod.GET)
    public Object selectOrderByPayNO(@PathVariable String payNO) throws Exception {
        return orderService.selectByOrderPayNO(payNO);
    }

    @ApiOperation(value = "按id查询订单详情[只查询订单信息，并查询本身的订单详情]")
    @RequestMapping(value = "detail/{orderID}/{userID}", method = RequestMethod.GET)
    public Object selectDetailByOrderID(@PathVariable Long orderID, @PathVariable Long userID) throws Exception {
        return orderService.selectByOrderID(orderID, userID, 2);
    }

    @ApiOperation(value = "获取预支付单号相关信息（payType 1微信app支付 2建行支付 3支付宝 4微信Js 5建行H5支付）【post数据orderID的List】")
    @RequestMapping(value = "/pay/{payType}", method = RequestMethod.POST)
    public Object pay(@RequestBody List<Long> orderIDList, @PathVariable Integer payType, HttpServletRequest request) {
        String userIp = CusAccessObjectUtil.getIpAddress(request);
        logger.info("微信支付iP:" + userIp);
        return orderService.pay(orderIDList, payType, userIp, "");
    }

    @ApiOperation(value = "获取预支付单号相关信息（payType 4微信JS支付）【post数据orderID的List】")
    @RequestMapping(value = "/pay/{payType}/{code}", method = RequestMethod.POST)
    public Object jsPay(@RequestBody List<Long> orderIDList, @PathVariable Integer payType, @PathVariable String code, HttpServletRequest request) {
        String userIp = CusAccessObjectUtil.getIpAddress(request);
        logger.info("微信支付iP:" + userIp);
        return orderService.pay(orderIDList, payType, userIp, code);
    }

    //TODO add for赣州 start
    @ApiOperation(value = "获取预支付单号相关信息（payType 1微信app支付 2建行支付 3支付宝 4微信Js 5建行H5支付）【post数据orderID的List】")
    @RequestMapping(value = "/gzpay/{payType}", method = RequestMethod.POST)
    public Object payForGz(@RequestBody GzPayDto gzPayDto, @PathVariable Integer payType, HttpServletRequest request) {
        String userIp = CusAccessObjectUtil.getIpAddress(request);
        logger.info("微信支付iP:" + userIp);
        return orderService.payForGz(gzPayDto, payType, userIp, "");
    }
    //add for赣州 end

    @ApiOperation(value = "零支付")
    @RequestMapping(value = "/zeroPay", method = RequestMethod.POST)
    public Object zeroPay(@RequestBody List<Long> orderIDList, HttpServletRequest request) {
        String userIp = CusAccessObjectUtil.getIpAddress(request);
        logger.info("微信支付iP:" + userIp);
        return orderService.zeroPay(orderIDList, 6);
    }

    @ApiOperation(value = "支付回调接口")
    @RequestMapping(value = "/rePay", method = RequestMethod.POST)
    public Object rePay(@RequestBody WxPayResultDto resultDto) {
        //SystemContext.getRequest().setAttribute("companyID",resultDto.getCompanyID());
        return orderService.rePay(resultDto);
    }

    @ApiOperation(value = "取消订单")
    @RequestMapping(value = "/cancel/{orderID}", method = RequestMethod.GET)
    public Object cancelOrder(@PathVariable Long orderID) {
        //Long companyID = SystemContext.getCompanyID();
        OrderStateDto orderStateDto = new OrderStateDto();
        orderStateDto.setOrderID(orderID);
        orderStateDto.setState(0);
        orderService.updateState(orderStateDto);
        return "success";
    }

    @ApiOperation(value = "添加物流运单号[需传物流公司官网URL]")
    @RequestMapping(value = "/logistics", method = RequestMethod.POST)
    public Object addLogistics(@RequestBody OrderLogistics logistics) {
        return orderService.addLogistics(logistics);
    }

    @ApiOperation(value = "ERP订单是否确认")
    @RequestMapping(value = "/isConfirm/{orderId}", method = RequestMethod.GET)
    public Object isConfirm(@PathVariable Long orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderId);
        if (orderInfo == null) {
            return "0";//未找到订单
        }
        if (orderInfo.getState() == 2) {
            return "2";
        } else {
            return "1";
        }

    }

    @ApiOperation(value = "ERP发货以及添加快递单号")
    @RequestMapping(value = "/ErpSendOrder", method = RequestMethod.POST)
    public Object ErpSendOrder(@RequestBody OrderLogistics logistics) {
        OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(logistics.getOrderID());
        if (orderInfo == null) {
            System.out.println("ERP订单为空?");
            return "0";
        } else {
            System.out.println("ERP订单不为空" + orderInfo.getState());
            if (orderInfo.getState() == 2) {
                return "2";
            } else if (orderInfo.getState() == 3) {
                //更新物流信息 add buyaodng
                orderService.addLogistics(logistics);
                OrderInfo order2 = orderInfoMapper.selectByPrimaryKey(logistics.getOrderID());

                OrderIndexStateDto indexStateDto1 = new OrderIndexStateDto();
                indexStateDto1.setOrderID(logistics.getOrderID().toString());
                indexStateDto1.setStatus(3);

                indexStateDto1.setPayTime(order2.getPayTime() + "");
                indexStateDto1.setPayType(order2.getPayType());
                indexStateDto1.setSendTime(System.currentTimeMillis() + "");
                indexStateDto1.setSureTime(order2.getSureTime() + "");
                indexStateDto1.setPayNO(order2.getPayNo());
                orderIndexService.updateState(indexStateDto1);

                return "1";
            }
        }
        orderService.addLogistics(logistics);
        logistics.setAddTime(System.currentTimeMillis());
        logistics.setId(0l);
        OrderStateDto orderStateDto = new OrderStateDto();
        orderStateDto.setOrderID(logistics.getOrderID());
        orderStateDto.setState(3);
        orderService.addLogistics(logistics);
        boolean result = orderService.updateState(orderStateDto);
        if (result) {
            return "1";
        } else {
            return "0";
        }
    }


    @ApiOperation(value = "定时任务订单失效")
    @RequestMapping(value = "/timeTaskOrderCancel", method = RequestMethod.GET)
    public Object timeTaskOrderCancel() {
        return orderService.timeTaskOrderCancel();
    }

    @ApiOperation(value = "定时任务生成结算记录")
    @RequestMapping(value = "/timetaskSettlement", method = RequestMethod.GET)
    public Object timetaskSettlement() {
        return orderService.timetaskSettlement(null, null);
    }

    @ApiOperation(value = "定时任务生成结算记录,手动传年月")
    @RequestMapping(value = "/timetaskSettlement/{year}/{month}", method = RequestMethod.GET)
    public Object timetaskSettlement(@PathVariable Integer year, @PathVariable Integer month) {
        return orderService.timetaskSettlement(year, month);
    }

    @ApiOperation(value = "定时任务生成供应商中收结算记录")
    @RequestMapping(value = "/timetaskSupplierSettlementByMonth", method = RequestMethod.GET)
    public Object timetaskSupplierSettlementByMonth() {
        return orderService.timetaskSupplierSettlementByMonth(null, null);
    }

    @ApiOperation(value = "定时任务生成供应商中收结算记录,手动传年月")
    @RequestMapping(value = "/timetaskSupplierSettlementByMonth/{year}/{month}", method = RequestMethod.GET)
    public Object timetaskSupplierSettlementByMonth(@PathVariable Integer year, @PathVariable Integer month) {
        return orderService.timetaskSupplierSettlementByMonth(year, month);
    }

    @ApiOperation(value = "定时任务生成供应商中收结算记录")
    @RequestMapping(value = "/timetaskSupplierSettlementByDay", method = RequestMethod.GET)
    public Object timetaskSupplierSettlementByDay() {
        return orderService.timetaskSupplierSettlementByDay(null, null, null);
    }

    @ApiOperation(value = "旧数据生成供应商中收结算记录,传入结算起始日期格式（2017-9-1）")
    @RequestMapping(value = "/timetaskSupplierSettlementByDay/{start}/{end}", method = RequestMethod.GET)
    public Object timetaskSupplierSettlement(@PathVariable String start, @PathVariable String end) {
        orderService.supplierSettlementByDay(start, end);
        return "success";
    }

    @ApiOperation(value = "供应商中收结算记录分页")
    @RequestMapping(value = "/supplierSettlements", method = RequestMethod.POST)
    public Object supplierSettlements(@RequestBody SupplierSettlementConditionDto conditionDto) {
        return orderService.supplierSettlementConditionDto(conditionDto);
    }

    @ApiOperation(value = "供应商中收结算按天统计")
    @RequestMapping(value = "/supplierSettlementDetail", method = RequestMethod.POST)
    public Object supplierSettlementDetail(@RequestBody SupplierSettlementSelectDetailDto conditionDto) {
        return orderService.supplierSettlementDetail(conditionDto);
    }

    @ApiOperation(value = "供应商中收结算订单明细分页")
    @RequestMapping(value = "/supplierSettlementOrderInfo", method = RequestMethod.POST)
    public Object supplierSettlementOrderInfo(@RequestBody SupplierSettlementSelectDetailDto conditionDto) {
        return orderService.supplierSettlementOrderInfo(conditionDto);
    }

    @ApiOperation(value = "中收结算")
    @RequestMapping(value = "/updateSupplierSettlement", method = RequestMethod.PUT)
    public Object updateSupplierSettlement(@RequestBody List<Long> idList) {
        //供应商结算
        return orderService.updateSupplierSettlementState(idList);
    }


    @ApiOperation(value = "定时任务发货超过7天则自动确认")
    @RequestMapping(value = "/timetaskOrderReceipt", method = RequestMethod.GET)
    public Object timetaskOrderReceipt() {
        return orderService.timetaskOrderReceipt();
    }

    @ApiOperation(value = "定时任务查询昨天订单满足规则增送金豆")
    @RequestMapping(value = "/yesterDayOrderUser", method = RequestMethod.GET)
    public Object yesterDayOrderUser() {
        return orderService.selectYesterDayOrderUser(null);
    }

    @ApiOperation(value = "[计算会员每日送金豆],手工调用")
    @RequestMapping(value = "/userPresent/{date}", method = RequestMethod.GET)
    public Object doUserPresentDate(@PathVariable String date) {
        return orderService.selectYesterDayOrderUser(date);
    }


    @ApiOperation(value = "获取昨天已生成支付单号未付款的支付单号及其金额")
    @RequestMapping(value = "/unpaidPayOrder", method = RequestMethod.GET)
    public Object getUnpaidPayOrder() {
        return orderService.getUnpaidPayOrder(null, null);
    }

    @ApiOperation(value = "获取指定时间已生成支付单号未付款的支付单号及其金额")
    @RequestMapping(value = "/unpaidPayTime/{startTime}/{endTime}", method = RequestMethod.GET)
    public Object getUnpaidPayOrderTime(@PathVariable Long startTime, @PathVariable Long endTime) {
        return orderService.getUnpaidPayOrder(startTime, endTime);
    }

    @ApiOperation(value = "订单发货")
    @RequestMapping(value = "/send/{orderID}", method = RequestMethod.GET)
    public Object orderSend(@PathVariable Long orderID) {
        OrderStateDto orderStateDto = new OrderStateDto();
        orderStateDto.setOrderID(orderID);
        orderStateDto.setState(3);
        orderService.updateState(orderStateDto);
        return "success";
    }

    @ApiOperation(value = "订单撤回到待发货")
    @RequestMapping(value = "/recall/{orderID}", method = RequestMethod.GET)
    public Object orderRecall(@PathVariable Long orderID) {
        OrderStateDto orderStateDto = new OrderStateDto();
        orderStateDto.setOrderID(orderID);
        orderStateDto.setState(5);
        orderService.recallOrderErp(orderStateDto);
        return "success";
    }

    @ApiOperation(value = "确认收货")
    @RequestMapping(value = "/receipt/{orderID}", method = RequestMethod.GET)
    public Object orderReceipt(@PathVariable Long orderID) {
        orderService.receive(orderID);
        return "success";
    }

    public static ResultData httpGet(String url, String secretKey) {
        System.out.println("http:" + url);
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        MediaType mediaType = new MediaType("application", "json", StandardCharsets.UTF_8);
        headers.setContentType(mediaType);
//        if(!Strings.isNullOrEmpty(key) && !Strings.isNullOrEmpty(value)){
        headers.set("secretKey", secretKey);
//        }
        HttpEntity<String> entity = new HttpEntity<String>("", headers);
        ResponseEntity<ResultData> result = restTemplate.exchange(url, HttpMethod.GET, entity, ResultData.class, "");
        return result.getBody();
    }

    @ApiOperation(value = "卖家发货前确认")
    @RequestMapping(value = "/sureOrder", method = RequestMethod.POST)
    public Object sureOrder(@RequestBody List<Long> orderIDList) {
        for (Long orderID : orderIDList) {
            OrderStateDto stateDto = new OrderStateDto();
            stateDto.setOrderID(orderID);
            stateDto.setState(5);
            orderService.updateState(stateDto);
        }
        return "success";
    }

    @ApiOperation(value = "按条件查询结算记录")
    @RequestMapping(value = "/settlementList", method = RequestMethod.POST)
    public Object selectSettlement(@RequestBody SettlementConditionDto settlement) {
        return orderService.selectSettlement(settlement);
    }

    @ApiOperation(value = "按年月状态查询结算统计数据")
    @RequestMapping(value = "/settlementCount", method = RequestMethod.POST)
    public Object selectSettlementCount(@RequestBody SettlementForCountDto countDto) {
        return orderService.selectSettlementCount(countDto);
    }

    @ApiOperation(value = "查询所有包含未结算资金的月份数据[type:1供应商，2银行分行]")
    @RequestMapping(value = "/getDataByState/{type}", method = RequestMethod.GET)
    public Object getDataByState(@PathVariable String type) throws Exception {
        return orderService.getDataByState(type);
    }

    @ApiOperation(value = "资金结算")
    @RequestMapping(value = "/settlement", method = RequestMethod.PUT)
    public Object updateSettlementState(@RequestBody List<Long> idList) {
        return orderService.updateSettlementState(idList);
    }

    @ApiOperation(value = "按供应商查询订单详情列表(只限于已完成订单，用于得到结算详情)")
    @RequestMapping(value = "/oiList/{sellerID}/{year}/{month}", method = RequestMethod.GET)
    public Object selectOrderAndItemList(@PathVariable Long sellerID, @PathVariable int year, @PathVariable int month) {
        return orderService.selectOrderAndItemList(sellerID, year, month, 1);
    }

    @ApiOperation(value = "按供应商查询订单详情列表(只限于已完成订单，用于得到结算详情)")
    @RequestMapping(value = "/oiListPage/{sellerID}/{year}/{month}/{pageNo}/{pageSize}", method = RequestMethod.GET)
    public Object selectOrderAndItemListPage(@PathVariable Long sellerID, @PathVariable int year, @PathVariable int month, @PathVariable int pageNo, @PathVariable int pageSize) {
        return orderService.selectOrderAndItemListPage(sellerID, year, month, 1, pageNo, pageSize);
    }

    @ApiOperation(value = "按分行ID查询订单详情列表(只限于已完成订单，用于得到结算详情)")
    @RequestMapping(value = "/orderList/{branchID}/{year}/{month}", method = RequestMethod.GET)
    public Object selectOrderList(@PathVariable Long branchID, @PathVariable int year, @PathVariable int month) {
        return orderService.selectOrderAndItemList(branchID, year, month, 2);
    }

    @ApiOperation(value = "供应商首页数据（订单统计、商品统计数据）")
    @RequestMapping(value = "/selectHomepageCount/{sellerID}", method = RequestMethod.GET)
    public Object selectHomepageCount(@PathVariable Long sellerID) {
        return orderService.selectHomepageCount(sellerID);
    }

    @ApiOperation(value = "供应商首页数据V2（统计销售数据）")
    @RequestMapping(value = "/selectHomepageCountV2/{sellerID}", method = RequestMethod.GET)
    public Object selectHomepageCountV2(@PathVariable Long sellerID) {
        return orderService.selectHomepageCountV2(sellerID);
    }

    @ApiOperation(value = "供应商商品订单数，商品销售额，排序orderBy(按订单数则orderQty，按销售额则salesTotal)")
    @RequestMapping(value = "/goodsSalesMore/{sellerID}/{orderBy}/{pageNum}/{pageSize}", method = RequestMethod.GET)
    public Object selectGoodsSalesMore(@PathVariable Long sellerID, @PathVariable String orderBy, @PathVariable int pageNum, @PathVariable int pageSize) {
        Map<String, Object> param = new HashMap<>();
        param.put("sellerID", sellerID);
        param.put("orderBy", orderBy);
        return orderService.selectGoodsSalesMore(pageNum, pageSize, param);
    }

    @ApiOperation(value = "按userID查询订单量、交易额[2销售经理，3销售顾问，4会员]")
    @RequestMapping(value = "/userTransAction/{userID}/{type}/{level}/{oID}", method = RequestMethod.GET)
    public Object userTransAction(@PathVariable Long userID, @PathVariable int type, @PathVariable int level, @PathVariable Long oID) {
        OrderCountDto countDto = new OrderCountDto();
        switch (type) {
            case 1:
                switch (level) {
                    case 2:
                        countDto.setBranchID(oID);
                        break;
                    case 3:
                        countDto.setTwoLevelBranchID(oID);
                        break;
                    case 4:
                        countDto.setSubbranchID(oID);
                        break;
                }
            case 2:
                countDto.setSalesManagerID(userID);
                break;
            case 3:
                countDto.setSalesID(userID);
                break;
            case 4:
                countDto.setUserID(userID);
                break;
        }

        OrderCountVo orderCountVo = orderService.selectOrderCount(countDto);
        int orderQty = orderCountVo.getOrderQty() == null ? 0 : orderCountVo.getOrderQty();
        int goodsQty = orderCountVo.getGoodsQty() == null ? 0 : orderCountVo.getGoodsQty();
        BigDecimal transactionTotal = orderCountVo.getTransactionTotal() == null ? BigDecimal.ZERO : orderCountVo.getTransactionTotal();
        Map<String, Object> param = new HashMap<>();
        param.put("orderQty", orderQty);
        param.put("goodsQty", goodsQty);
        param.put("transactionTotal", transactionTotal);
        return param;
    }

    @ApiOperation(value = "索引纠错记录接口")
    @RequestMapping(value = "/esLog", method = RequestMethod.POST)
    public Object recordEsLog(@RequestBody List<OrderIndexStateDto> orderList) {
        for (OrderIndexStateDto orderDto : orderList) {
            OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(Long.parseLong(orderDto.getOrderID()));
            if (orderInfo == null) {
                ErrorEs errorEs = new ErrorEs();
                errorEs.setId(IdGen.get().nextId());
                errorEs.setType(2);
                errorEs.setObjectID(Long.parseLong(orderDto.getOrderID()));
                errorEs.setReason(1);
                errorEsMapper.insert(errorEs);
            } else {
                if (!orderDto.getStatus().equals(orderInfo.getState())) {
                    ErrorEs errorEs = new ErrorEs();
                    errorEs.setId(IdGen.get().nextId());
                    errorEs.setType(2);
                    errorEs.setObjectID(Long.parseLong(orderDto.getOrderID()));
                    errorEs.setReason(2);
                    errorEsMapper.insert(errorEs);
                }
            }
        }
        return "success";
    }

    @ApiOperation(value = "一键建立所有索引")
    @RequestMapping(value = "/addAllIndex", method = RequestMethod.GET)
    public Object addAllIndex() {
        return orderService.addAllIndex();
    }

    @ApiOperation(value = "删除索引")
    @RequestMapping(value = "/delAllIndex", method = RequestMethod.GET)
    public Object delAllIndex() {
        return orderService.delAllIndex();
    }

    @ApiOperation(value = "一键建立所有索引-payNo")
    @RequestMapping(value = "/addPayNoIndex", method = RequestMethod.GET)
    public Object addPayNoIndex() {
        return orderService.addPayNoIndex();
    }

    @ApiOperation(value = "一键建立所有索引-companyID")
    @RequestMapping(value = "/addCompanyIndex", method = RequestMethod.GET)
    public Object addCompanyIndex() {
        return orderService.addOrderIndexCompanyID();
    }

    @ApiOperation(value = "按银行ID仅查询本部订单详情列表(已付款订单，用于银行对账单详情)")
    @RequestMapping(value = "/orderItemList/{oID}/{year}/{month}/{pageNo}/{pageSize}", method = RequestMethod.GET)
    public Object selectOrderItemListBySelf(@PathVariable String oID, @PathVariable int year, @PathVariable int month,
                                            @PathVariable int pageNo, @PathVariable int pageSize) {
        return orderService.selectOrderItemListBySelf(oID, year, month, pageNo, pageSize);
    }

    @ApiOperation(value = "按银行ID、供应商ID查询本部以及子部门订单详情列表(已付款单据，用于银行对账单详情)")
    @RequestMapping(value = "/orderItemListToSeller/{oID}/{year}/{month}/{pageNo}/{pageSize}/{supplierID}", method = RequestMethod.GET)
    public Object selectOrderItemListBySelf(@PathVariable String oID, @PathVariable int year, @PathVariable int month,
                                            @PathVariable int pageNo, @PathVariable int pageSize, @PathVariable Long supplierID) {
        return orderService.selectOrderItemListBySpplier(oID, year, month, pageNo, pageSize, supplierID);
    }

    @ApiOperation(value = "按银行ID、供应商ID查询本部门订单详情列表(已付款单据，用于银行对账单详情)")
    @RequestMapping(value = "/selectSupplierOrderItemSelf/{oID}/{year}/{month}/{pageNo}/{pageSize}/{supplierID}", method = RequestMethod.GET)
    public Object selectSupplierOrderItemListSelf(@PathVariable String oID, @PathVariable int year, @PathVariable int month,
                                                  @PathVariable int pageNo, @PathVariable int pageSize, @PathVariable Long supplierID) {
        return orderService.selectSupplierOrderItemListSelf(oID, year, month, pageNo, pageSize, supplierID);
    }

    @ApiOperation(value = "按银行ID导出清单")
    @RequestMapping(value = "/detailList/{oID}/{year}/{month}", method = RequestMethod.GET)
    public Object getDetailList(@PathVariable String oID, @PathVariable int year, @PathVariable int month) {
        return orderService.getDetailList(oID, year, month, null);
    }

    @ApiOperation(value = "按银行ID、供应商ID导出清单,供应商端")
    @RequestMapping(value = "/detailListToSeller/{oID}/{year}/{month}/{supplierID}", method = RequestMethod.GET)
    public Object getDetailList(@PathVariable String oID, @PathVariable int year, @PathVariable int month, @PathVariable Long supplierID) {
        return orderService.getDetailList(oID, year, month, supplierID);
    }

    @ApiOperation(value = "按银行ID、供应商ID导出清单,仅本部")
    @RequestMapping(value = "/detailListToSellerSelf/{oID}/{year}/{month}/{supplierID}", method = RequestMethod.GET)
    public Object getDetailListSelf(@PathVariable String oID, @PathVariable int year, @PathVariable int month, @PathVariable Long supplierID) {
        return orderService.getDetailListSelf(oID, year, month, supplierID);
    }

    @ApiOperation(value = "抛转订单统计的数据源")
    @RequestMapping(value = "/getMaintenance", method = RequestMethod.GET)
    public Object getMaintenance() {
        List<CountOrder> addList = new ArrayList<>();
        DataResult result = HttpUtil.httpGet(ProConstants.getMaintenance, restTemplate);
        if (result.getIsSuccess() == 1 && result.getData() != null) {

            List<Map<String, String>> list = (List<Map<String, String>>) result.getData();

            CountOrder countHead = new CountOrder();
            countHead.setId(1l);
            countHead.setTotalAmount(new BigDecimal(0));
            countHead.setOrderCount(0);
            countHead.setUpdateTime(System.currentTimeMillis());
            CountOrder countHead2 = new CountOrder();
            countHead2.setId(0l);
            countHead2.setTotalAmount(new BigDecimal(0));
            countHead2.setOrderCount(0);
            countHead2.setUpdateTime(System.currentTimeMillis());
            addList.add(countHead);
            addList.add(countHead2);

            for (Map<String, String> map : list) {
                CountOrder countOrder = new CountOrder();
                countOrder.setId(IdGen.get().nextId());
                countOrder.setBranchID(map.get("branchID") != null ? Long.parseLong(map.get("branchID")) : 0);
                countOrder.setTwoLevelBranchID(map.get("twoLevelBranchID") != null ? Long.parseLong(map.get("twoLevelBranchID")) : 0);
                countOrder.setSubbranchID(map.get("subbranchID") != null ? Long.parseLong(map.get("subbranchID")) : 0);
                countOrder.setSalesManagerID(map.get("salesManagerID") != null ? Long.parseLong(map.get("salesManagerID")) : 0);
                countOrder.setTotalAmount(new BigDecimal(0));
                countOrder.setOrderCount(0);
                countOrder.setUpdateTime(System.currentTimeMillis());
                countOrder.setCompanyID(SystemContext.getCompanyID());
                addList.add(countOrder);
            }

        }
        //再写一个批量插入的请求就可以了
        countOrderMapper.insertBatch(addList);
        return null;
    }


    @ApiOperation(value = "抛转旧订单数据ERP")
    @RequestMapping(value = "/updateOldErpOrderInfo", method = RequestMethod.GET)
    public Object updateOldInfo() {
        return orderService.updateOldErpOrderInfo();
    }

    @ApiOperation(value = "单独抛转三条")
    @RequestMapping(value = "/updateOldErpOrderInfoSome", method = RequestMethod.GET)
    public Object updateOldInfoThrInfo() {
        return orderService.updateOldErpOrderInfoSome();
    }
    //updateOldErpOrderInfoSome


    //=======create by zll 抛转以前的order_info里面的address信息
    @ApiOperation(value = "抛转以前的旧数据地址信息")
    @RequestMapping(value = "/updateOldOrderInfo", method = RequestMethod.GET)
    public Object updateAddressInfo() {
        return orderService.updateOrderOldAddressInfo();
    }


    @ApiOperation(value = "手动抛转错误的单号")
    @RequestMapping(value = "/updateErpErrorDataByPayNo/{payNo}", method = RequestMethod.GET)
    public Object updateErpErrorDataByPayNo(@PathVariable String payNo) {
        return orderService.updateErpErrorDataByPayNo(payNo);
    }

    @ApiOperation(value = "根据订单号手动抛转--慎用")
    @RequestMapping(value = "/updateErpErrorDataByOrderId/{orderId}", method = RequestMethod.GET)
    public Object updateErpErrorDataByOderId(@PathVariable Long orderId) {
        return orderService.updateErpErrorDataByOderId(orderId);
    }

    @ApiOperation(value = "手动一次性抛转错误的数据")
    @RequestMapping(value = "/updateErpErrorData", method = RequestMethod.GET)
    public Object updateErpErrorData() {
        return orderService.updateErpErrorData();
    }

    @ApiOperation(value = "得到未成功的数量--Erp")
    @RequestMapping(value = "/getErrorCount", method = RequestMethod.GET)
    public Object getErrorCount() {
        return orderService.getErrorCount();
    }

    @ApiOperation(value = "订单支付前验证")
    @RequestMapping(value = "/orderValid/{orderID}", method = RequestMethod.GET)
    public Object orderValid(@PathVariable Long orderID) throws Exception {
        return orderService.orderValid(orderID);
    }


    @ApiOperation(value = "对账报表导出")
    @RequestMapping(value = "/orderDetailForExport", method = RequestMethod.POST)
    public Object orderDetailForExport(@RequestBody OrderExportDto exportDto) {
        return orderService.OrderDetailForExport(exportDto);
    }

    @ApiOperation(value = "订单核销")
    @RequestMapping(value = "/orderCheck", method = RequestMethod.POST)
    public Object orderCheck(@RequestBody OrderCheckDto orderCheck) {
        return orderService.orderCheck(orderCheck);
    }

    @ApiOperation(value = "订单撤销")
    @RequestMapping(value = "/orderCheckOff", method = RequestMethod.POST)
    public Object orderCheckOff(@RequestBody OrderCheckDto orderCheck) {
        return orderService.orderCheckOff(orderCheck);
    }

    @ApiOperation(value = "线下订单定时任务获取今天过期订改成已失效")
    @RequestMapping(value = "/orderStateOffline", method = RequestMethod.GET)
    public Object updateOrderStateOffline() {
        return orderService.updateOrderStateOffline(null);
    }

    @ApiOperation(value = "启动 线下订单定时任务获取今天今天过期订改成已失效")
    @RequestMapping(value = "/setupOrderStateOffline", method = RequestMethod.GET)
    public Object setupCronJobOrderStateOffline() {
        return orderService.setupCronJobOrderStateOffline();
    }

    @ApiOperation(value = "线下订单定时任务获取今天过期订改成已失效-手动")
    @RequestMapping(value = "/orderStateOfflineCheck/{date}", method = RequestMethod.GET)
    public Object orderStateOfflineCheck(@PathVariable String date) {
        return orderService.updateOrderStateOffline(date);
    }

    @ApiOperation(value = "一键建立所有索引-orderPayType")
    @RequestMapping(value = "/addPayNoIndexTest", method = RequestMethod.GET)
    public Object addPayNoIndexTest() {
        return orderService.addPayNoIndexTest();
    }

    @ApiOperation(value = "查询订单套账信息")
    @RequestMapping(value = "/erp/{orderID}", method = RequestMethod.GET)
    public Object selectCompanyIDByOrderID(@PathVariable Long orderID) throws Exception {
        return orderService.selectCompanyIDByOrderID(orderID);
    }

    @ApiOperation(value = "查询订单套账信息")
    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public Object test() throws Exception {
        return orderService.getGoldenGoodsID();
    }

    @ApiOperation(value = "支付时计算(confirm 1:重新计算单据去支付0:验证价格是否变化)")
    @RequestMapping(value = "/calculationOrder/{orderID}/{confirm}", method = RequestMethod.GET)
    public Object calculationOrder(@PathVariable Long orderID, @PathVariable Integer confirm) {
        return orderService.calculationOrder(orderID, confirm, false);
    }

    @ApiOperation(value = "支付时计算(confirm 1:重新计算单据去支付0:验证价格是否变化)")
    @RequestMapping(value = "/b2b/calculationOrder/{orderID}/{confirm}", method = RequestMethod.GET)
    public Object calculationOrderForB2b(@PathVariable Long orderID, @PathVariable Integer confirm) {
        return orderService.calculationOrder(orderID, confirm, true);
    }

    @ApiOperation(value = "查看部门单据")
    @RequestMapping(value = "/selectDeptOrder/{oID}/{level}", method = RequestMethod.GET)
    public Object selectDeptRecord(@PathVariable Long oID, @PathVariable Integer level) {
        return orderService.selectDeptRecord(oID, level);
    }

    @ApiOperation(value = "更新订单的部门信息")
    @RequestMapping(value = "/moveDeptOrderToNewDept/{oID}/{level}", method = RequestMethod.GET)
    public Object updateDeptOrderToNewDept(@PathVariable Long oID, @PathVariable Integer level) {
        return orderService.updateDeptOrderToNewDept(oID, level);
    }

    @RequestMapping(value = "/testa", method = RequestMethod.GET)
    public Object testa() {
        return CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.ACCOUNTCODE.getCode());
    }

    @ApiOperation(value = "复制下单获取商品最新信息快照")
    @RequestMapping(value = "/testComm/{orderID}", method = RequestMethod.GET)
    public Object testComm(@PathVariable Long orderID) throws Exception {
        OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderID);
        return commissionUserService.addCommissionV3(orderInfo);
    }
}
